package com.ny.controller;

import com.ny.entity.Result;
import com.ny.entity.User;
import com.ny.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @GetMapping("/selectAllUser")
    public Result selectAllUser(){
        return Result.success(userService.fillAllUser());
    }
    //登录
    /*@PostMapping("/login")
    public Result login(String username,String password){
        User user = userService.login(username,password);
        return user == null ? Result.error("用户名或密码错误") : Result.success(user);
    }*/
    //根据用户名查询用户
    //http://localhost:8080/findByUsername?username=admin
    @GetMapping("/findByUsername")
    public Result findByUsername(String username){
        User user = userService.findByUsername(username);
        return user == null ? Result.error("用户不存在") : Result.success(user);
    }
    @PostMapping("/register")
    public Result register(User user){
        return Result.success(userService.insertUser(user));
    }
    //查询邮箱是否存在
    @GetMapping("/findByEmail")
    public Result findByEmail(String email){
        User user = userService.findByEmail(email);
        return user == null ? Result.error("邮箱不存在") : Result.success(user);
    }
    //http://localhost:8089/findByEmail?email=<EMAIL>
    @GetMapping("/sendEmailCode")
    public Result sendEmailCode(String email){
        User user = userService.findByEmail(email);
        if (user != null){
            userService.sendEmailCode(email);
            return Result.success("验证码发送成功");
        }else
        {
            return Result.notFound("邮箱不存在");
        }
    }
    //http://localhost:8089/sendEmailCode?email=<EMAIL>
    //修改密码
    @PutMapping("/updatePassword")
    public Result updatePassword(String email,String code,String password){
        Boolean checkCode =userService.checkCode(email, code);
        if (checkCode){
            int i =userService.updatePasswordByEmail(email, password);
            if (i>0){
                return Result.success("修改成功");
            }
            return Result.notFound("成功获取验证码");
        }
        else {
            return Result.success("验证码错误");
        }
    }
    //http://localhost:8089/updatePassword?email=<EMAIL>&code=1234&password=123456
}
